//
//  AppActionSheet.swift
//  app
//
//  Created by g1 on 2023/9/20.
//

import UIKit

struct AppActionSheetItem {
    
    var title: String
    var titleColor: UIColor
    var titleFont: UIFont
    
    init(title: String, titleColor: UIColor = .app_black, titleFont: UIFont = kSetPingFangRegular(17)) {
        self.title = title
        self.titleColor = titleColor
        self.titleFont = titleFont
    }
}

class AppActionSheet: UIView, UITableViewDelegate, UITableViewDataSource {
    
    private let rootView = UIApplication.shared.keyWindow!
    private var backgroundView: UIView = UIView()
    
    private var actionItems = [AppActionSheetItem]()
    private var selectCompleteHolder: ((_ title: String, _ index: Int) -> Void)?
    
    init(titles: [AppActionSheetItem], selectCompleteHandle: @escaping (_ title: String, _ index: Int) -> Void) {
        
        super.init(frame: .zero)
        
        actionItems = titles
        selectCompleteHolder = selectCompleteHandle
        configUI()
        
    }
    private func getHeight() -> CGFloat {
        let bottomSpace: CGFloat = actionItems.count > 8 ? 10:0
        return CGFloat(min(8, actionItems.count) * 56 + 10 + 56) + bottomSpace
    }
    
    // MARK: - UITableViewDelegate,UITableViewDataSource
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 56
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return actionItems.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(AppActionSheetTableViewCell.self)
        cell.setItem(actionItems[indexPath.item])
        return cell;
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if let holder = selectCompleteHolder, indexPath.section == 0 {
            holder(indexPath.section == 1 ? "": actionItems[indexPath.item].title, indexPath.section == 1 ? -1 : indexPath.row)
        }
        hide()
        
    }
    
    // MARK: - configUI
    func configUI() {
        
        // 防止多个 AlertView 重复显示
        if rootView.subviews.filter({ $0.isKind(of: AppActionSheet.self) }).count > 0 { return }
                
        backgroundView = UIView()
        backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0)
                
        actionSheetTableView = UITableView()
        actionSheetTableView.delegate = self
        actionSheetTableView.dataSource = self
        actionSheetTableView.tableFooterView = UIView()
        actionSheetTableView.showsVerticalScrollIndicator = false
        actionSheetTableView.backgroundColor = .clear
        actionSheetTableView.separatorStyle = .none
        //        actionSheetTableView.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        actionSheetTableView.register(cellClass: AppActionSheetTableViewCell.self)
        
        rootView.addSubview(backgroundView)
        rootView.addSubview(self)
        addSubview(backView)
        backView.addSubview(cornerBackView)
        cornerBackView.addSubview(cancelBtn)
        cornerBackView.addSubview(lineView)
        cornerBackView.addSubview(actionSheetTableView)
        
        loadLayout()
        self.rootView.layoutIfNeeded()
        
        let tapGR = UITapGestureRecognizer.init(target: self, action: #selector(hideAction))
        backgroundView.addGestureRecognizer(tapGR)

    }
    func loadLayout() {
        
        backgroundView.snp.makeConstraints { (make) in
            make.edges.equalTo(rootView)
        }
        
        let height = getHeight()
        snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(height + 20)
            make.bottom.equalTo(height + 20)
        }
        backView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        cornerBackView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(height)
        }
        cancelBtn.snp.makeConstraints { make in
            make.height.equalTo(56)
            make.bottom.left.width.equalToSuperview()
        }
        lineView.snp.makeConstraints { make in
            make.height.equalTo(10)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(cancelBtn.snp.top)
        }
        actionSheetTableView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(lineView.snp.top).offset(actionItems.count > 8 ? -10:0)
        }
        
        actionSheetTableView.isScrollEnabled = false
        cancelBtn.addTarget(self, action: #selector(hideAction), for: .touchUpInside)
    }
    private lazy var backView: UIView = {
        let backView = UIView()
        backView.backgroundColor = .white
        return backView
    }()
    private lazy var cornerBackView: UIView = {
        let cornerBackView = UIView()
        cornerBackView.backgroundColor = .white
        return cornerBackView
    }()
    private lazy var actionSheetTableView = UITableView(frame: .zero)
    private lazy var lineView: UIView = {
        let lineView = UIView()
        lineView.backgroundColor = .app_viewBackgroundColor
        return lineView
    }()
    private lazy var cancelBtn: AppCustomButton = {
        let cancelBtn = AppCustomButton()
        cancelBtn.setTitle("取消".localized, for: .normal)
        cancelBtn.setTitleColor( .black, for: .normal)
        cancelBtn.backgroundColor = .white
        return cancelBtn
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension AppActionSheet: UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        
        if let view = touch.view, view.isDescendant(of: actionSheetTableView) {
            return false
        }
        
        return true
    }
    
    func show() {
        
        self.backView.layerCornerRadius(16, [.topLeft,.topRight])
        UIView.animate(withDuration: 0.2, animations: {
            
            self.backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            self.snp.updateConstraints { make in
                make.bottom.equalTo(0)
            }
            self.rootView.layoutIfNeeded()
        })

    }
    
    @objc private func hideAction() {
        hide()
    }
    
    private func hide(completion: (() -> Void)? = nil) {
        
        UIView.animate(withDuration: 0.2, animations: {
            self.backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0)
            self.snp.updateConstraints { make in
                make.bottom.equalTo(self.getHeight() + Size.safeAreaBottomGap)
            }
            self.rootView.layoutIfNeeded()
        }) { finished in
            guard finished else { return }
            self.removeFromSuperview()
            self.backgroundView.removeFromSuperview()
        }
        
    }
        
}



class AppActionSheetTableViewCell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        configUI()
    }
    
    func setItem(_ item: AppActionSheetItem) {
        titleLabel.text = item.title
        titleLabel.textColor = item.titleColor
        titleLabel.font = item.titleFont
    }
    
    // MARK: - configUI
    func configUI() {
        
        backgroundColor = .white
        selectionStyle = .none
        contentView.addSubview(backView)
        backView.addSubview(titleLabel)
        
        backView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.bottom.equalToSuperview()
        }
        titleLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
    }
    private lazy var backView: UIView = {
        let backView = UIView()
        return backView
    }()
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.font = kSetPingFangRegular(16)
        return titleLabel
    }()
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
}


